<?php

namespace app\admin\model\finance;

use think\Model;

class Spendingbudget extends Model
{

    // 表名
    protected $name = 'finance_spending_budget';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'mth_text',
        'balance_arr',
    ];

    public function getMthList()
    {
        return ['1' => __('Mth 1'), '2' => __('Mth 2'), '3' => __('Mth 3'), '4' => __('Mth 4'), '5' => __('Mth 5'), '6' => __('Mth 6'), '7' => __('Mth 7'), '8' => __('Mth 8'), '9' => __('Mth 9'), '10' => __('Mth 10'), '11' => __('Mth 11'), '12' => __('Mth 12')];
    }

    public function getMthTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['mth']) ? $data['mth'] : '');
        $list = $this->getMthList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getBalanceArrAttr($value, $data)
    {
        $starttime = strtotime($data['yer'] . '-' . $data['mth']);
        $endtime = strtotime('next month', $starttime) - 1;
        $total = Spendinglog::where(['status' => 'audited'])->where('datatime', 'between time', [$starttime, $endtime])->sum('amount');
        return ['total' => $total, 'balance' => $total - $data['amount']];
    }
}